--
-- Author: ping.wang
-- Date: 2018-09-19 18:03:57
--
-- CrystalInlayView
-- 水晶镶嵌界面

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)
local string_format = string.format
local IconSimpleRender = require("app.widget.renders.IconSimpleRender")
local IconRender = require("app.widget.renders.IconRender")
local CrystalSocketRender = import(".renders.CrystalSocketRender")
local table_insert = table.insert
local newFloatTipsView = require("app.newFloatTips.newFloatTipsView")
local ListViewVertical = require("app.widget.listview.ListViewVertical")


ClassRef.VIEW_ROOT_RES = Res.CrystalInlayView

function ClassRef:init()

    self._ui["Panel/Panel_right/Button_close"]:addClickEventListener(function()
        self:closeView(false)
    end)
    self._jingtongAtkValue = {0,0,0,0}
    self._jingtongDefValue = {0,0,0,0}

    local params = {
        renderClass = IconRender,
        isMultipleLayer = true, --分层加载 renderClass的Panel下子节点的个数
        perNum = 5,
        cellEventProxy = function(eventName, iconRd)
            self._scrollView:foreachVisibleCellModels(
            function(model, renderData)
                if model.cell then
                    model.cell:setSelected(false)
                else
                    model:setUIState("selected", false)
                end
            end)
            iconRd:setSelected(true)
            local tmpData = iconRd:getData()
            executeFunc(self._onOperate, "showCrystalTips", {render = iconRd,crystalId = tmpData:getId(),
                equipUid = self._data, crystalUid = tmpData:getUid()})
        end,
    }
    --所有可镶嵌的水晶的容器
    self._scrollView = ListViewVertical.new( self._ui.Panel_right:findChild("ScrollView"), params )


    self._leftPanel = self._ui.Panel_left

    self._equipTips = self._leftPanel:findChild("Panel_top/tip") --已镶嵌：Y/X

    self._wingRenders = {}
    for i = 1, 6 do
        local render = CrystalSocketRender.create(self._ui["Panel/Panel_left/Panel_top/Panel_socket/icon_"..i])
        table_insert(self._wingRenders,render)
        render:setData()
        render:setEquipUid(self._data)
    end

    for i = 1, 4 do
        local jingtongPanel = self._ui["Panel/Panel_left/Panel_bom/Panel_"..i]
        jingtongPanel:findChild("name"):setString(L(string_format("zhuanjing_%d",i)))
        jingtongPanel:setTouchEnabled(true)
        display.uiAddClick( jingtongPanel, function()
            local posTemp = jingtongPanel:convertToWorldSpace(cc.p(0,0))
            local width, height = jingtongPanel:getContentSize2()
            posTemp.y = posTemp.y + height
            executeFunc(self._onOperate, "showJingTongTips", {L(string_format("zhuanjing_%d",i))
                ,string_format(L("rockTips_7_"..i),self._jingtongAtkValue[i]/100,self._jingtongDefValue[i]/(10000 + self._jingtongDefValue[i]) * 100 ),posTemp} )
        end )
    end

    self:refresh()
end

function ClassRef:refresh()

    local equipData = UD:getEquip( self._data )
    if not equipData then
        equipData = UD:getItem( self._data )
    end

    if not equipData then
        dump("error the equipuid is inVailed ".. self._data)
        return
    end


    self._leftPanel:findChild("Panel_top/name"):setString(equipData:getName(true))
    local icon = IconSimpleRender.create(self._leftPanel:findChild("Panel_top/icon"))
    icon:setData(equipData)

    --填充右侧的scrollView
    local scrollViewData = {}
    for k, v in pairs(UD:getItems()) do
        if v.itemBagType == Enums.ItemBagType.item and v:getItemType() == Enums.ItemType.crystal then
            table_insert(scrollViewData, v)
        end
    end
    --需要排序所有的水晶

    table.sort(scrollViewData,function(a,b)
        local rockInfoA = GD:queryRockById(a:getId())
        local rockInfoB = GD:queryRockById(b:getId())
        if tonumber(rockInfoA.leve) == tonumber(rockInfoB.leve) then
            return tonumber(rockInfoA.type) < tonumber(rockInfoB.type)
        else
            return tonumber(rockInfoA.leve) > tonumber(rockInfoB.leve)
        end
    end)

    self._scrollView:reloadData(scrollViewData)

    self._equipTips:setString(string_format(L("rockTips_1"), #equipData:getAllCrystalSlots(), equipData:getRockNum()))
    local num = equipData:getRockNum()
    local rockSlots = equipData:getAllCrystalSlots()
    local rockInfo = nil
    --四种精通
    local jingtongValue = {0,0,0,0}
    self._jingtongAtkValue = {0,0,0,0}
    self._jingtongDefValue = {0,0,0,0}
    for i = 1, 6 do
        local render = self._wingRenders[i]
        if i<= num then
            if rockSlots[i] then
                rockInfo = GD:queryRockById(rockSlots[i])
                jingtongValue[tonumber(rockInfo.type)] = jingtongValue[tonumber(rockInfo.type)] + tonumber(rockInfo.showValue)
                self._jingtongAtkValue[tonumber(rockInfo.type)] = self._jingtongAtkValue[tonumber(rockInfo.type)] + tonumber(rockInfo.attrVal1)
                self._jingtongDefValue[tonumber(rockInfo.type)] = self._jingtongDefValue[tonumber(rockInfo.type)] + tonumber(rockInfo.attrVal2)

                render:setData(rockSlots[i])
            else
                render:setData(0)
            end
        else
            render:setData()
        end
    end

    display.autoAdjustNodesPosX( self._ui["Panel/Panel_left/Panel_top/Panel_socket"]:getContentSize().width, self._wingRenders, num )

    --精通显示
    local panelBom = self._ui["Panel/Panel_left/Panel_bom"]
    for i = 1, 4 do
        panelBom:findChild("Panel_"..i.."/num"):setString(jingtongValue[i])
    end
end

function ClassRef:onOperate(cb)
    self._onOperate = cb
    for i = 1, 6 do
        local render = self._wingRenders[i]
        render:onBtnClick(self._onOperate)
    end
end

function ClassRef:showTips(render, leftParams, rightParams)
    if self._bounceing then
        return
    end
    if self._renderTemp then
        self:clearTips(true)
    end
    self._renderTemp = render

    local closeCallBack = function()
        self:clearTips()
    end

    local boundingBoxTemp = nil
    if render then
        boundingBoxTemp = render:getBoundingBox()
        local worldPosTemp = render:getParent():convertToWorldSpace( cc.p( boundingBoxTemp.x, boundingBoxTemp.y ) )
        boundingBoxTemp.x = worldPosTemp.x
        boundingBoxTemp.y = worldPosTemp.y
    end

    if leftParams then
        leftParams.notAutoHide = true
        leftParams.closeCallBack = closeCallBack

        if not self._leftTip then
            self._leftTip = newFloatTipsView.new( leftParams )
            self:addChild(self._leftTip, 200)
            display.adjustNodePos( boundingBoxTemp, self._leftTip.mUINode, 10 )
        else
            self._leftTip:refreshContent( leftParams )
            display.adjustNodePos( boundingBoxTemp, self._leftTip.mUINode, 10 )
        end
        self._leftTip:setVisible( true )
    end
    if rightParams then
        rightParams.notAutoHide = true
        rightParams.closeCallBack = closeCallBack
        if not self._rightTip then
            self._rightTip = newFloatTipsView.new( rightParams )
            self:addChild(self._rightTip,200)
            display.adjustNodePos( boundingBoxTemp, self._rightTip.mUINode, 10 )
        else
            self._rightTip:refreshContent( rightParams )
            display.adjustNodePos( boundingBoxTemp, self._rightTip.mUINode, 10 )
        end
        self._rightTip:setVisible( true )

        if self._leftTip and self._leftTip:isVisible() then -- 出现比较的情况
            local leftTipPosX = self._leftTip.mUINode:getPositionX()
            local leftTipSize = self._leftTip.mUINode:getContentSize()
            local leftTipHeight = leftTipSize.height

            local rightTipsPosX = self._rightTip.mUINode:getPositionX()
            local rightTipsPosY = self._rightTip.mUINode:getPositionY()
            local rightTipsSize = self._rightTip.mUINode:getContentSize()
            local rightTipsWidth = rightTipsSize.width
            local rightTipsHeight = rightTipsSize.height

            local leftPosX = leftTipPosX - rightTipsWidth
            local offsetX = 0
            if 10 > leftPosX then -- 左越界？
                offsetX = 10 - leftPosX
                leftPosX = 10
            end
            self._leftTip.mUINode:setPositionX( leftPosX )
            if rightTipsHeight > leftTipHeight then
                self._leftTip.mUINode:setPositionY(self._rightTip.mUINode:getPositionY() + rightTipsHeight - leftTipHeight)
            end
            self._rightTip.mUINode:setPositionX( rightTipsPosX + offsetX )
        end
    end

    -- 自动隐藏逻辑
    local nodeList = {}
    if self._leftTip and self._leftTip:isVisible() then -- 左侧tips可见
        table.insert( nodeList, self._leftTip.bg:getChildByName("bg") )
    end
    if self._rightTip and self._rightTip:isVisible() then -- 右侧tips可见
        table.insert( nodeList, self._rightTip.bg:getChildByName("bg") )
    end
    self._handlerTemp = display.nodeListRemoveForNotHit(nodeList, function()
        cc.Director:getInstance():getEventDispatcher():removeEventListener( self._handlerTemp )
        self._handlerTemp = nil

        if self._leftTip and self._leftTip:isVisible() then -- 左侧tips可见
            self._leftTip._fromBtnTips:hide()
            self._leftTip:setVisible(false)
        end
        if self._rightTip and self._rightTip:isVisible() then -- 左侧tips可见
            self._rightTip._fromBtnTips:hide()
            self._rightTip:setVisible(false)
        end
        self:clearTips()
    end)

    if not self._floatTipBg then -- 创建tipsBg
        self._floatTipBg = display.newColorLayer(cc.c4b(0,0,0,255*0.45))
        self:addChild(self._floatTipBg,199)
    end
    if (self._leftTip and self._leftTip:isVisible()) or (self._rightTip and self._rightTip:isVisible()) then -- 有任一tips显示状态
        -- print( " --------------->>> 显示tips" )
        self._floatTipBg:setVisible(true)
        -- 以下：将 render 中的panel抽到 self._floatTipBg
        local renderPanelTemp = render:getChildByName( "Panel" )
        local renderTempBg = self._floatTipBg:getChildByName( "Panel" )
        if renderPanelTemp then -- 原render子控件存在？
            self._renderPosTemp = cc.p( renderPanelTemp:getPosition() )
            if renderTempBg then -- _floatTipBg子控件存在？
                renderTempBg:removeFromParent()
            end
            renderPanelTemp:retain()
            renderPanelTemp:removeFromParent( false )
            self._floatTipBg:addChild(renderPanelTemp)
            renderPanelTemp:setScale( render:getScale() )
            renderPanelTemp:setPosition( cc.p( boundingBoxTemp.x, boundingBoxTemp.y ) )
            renderPanelTemp:release()

        end
    else
        self._floatTipBg:setVisible(false)
    end
end


function ClassRef:clearTips()
    if self._rightTip then
        self._rightTip:setVisible( false )
    end
    if self._leftTip then
        self._leftTip:setVisible( false )
    end
    if self._floatTipBg then
        --清空右侧选中
        if self._scrollView and self._floatTipBg:isVisible() then
            self._scrollView:foreachVisibleCellModels(
                function(model, renderData)
                    if model.cell then
                        model.cell:setSelected(false)
                    else
                        model:setUIState("selected", false)
                    end
                end)
        end

        self._floatTipBg:setVisible( false )
        -- 以下：归还被抽到 self._floatTipBg 中的panel
        local renderPanelTemp = self._renderTemp:getChildByName( "Panel" )
        local renderTempBg = self._floatTipBg:getChildByName( "Panel" )
        if renderPanelTemp then -- 原render子控件存在？
            if renderTempBg then -- _floatTipBg子控件存在？
                renderTempBg:removeFromParent()
            end
        else
            if renderTempBg then -- _floatTipBg子控件存在？
                renderTempBg:retain()
                renderTempBg:removeFromParent(false)
                self._renderTemp:addChild(renderTempBg)
                renderTempBg:setPosition( self._renderPosTemp )
                renderTempBg:setScale( 1 )
                renderTempBg:release()
            end
        end
    end
end

return ClassRef
